<template>
  <el-dialog title="优惠券配置" :visible.sync="dialogVisible" width="800">
    <el-form :model="couponForm" label-position="right" label-width="100px" ref="couponForm" v-if="pageType === 'form'"
      :rules="rules">
      <el-row :gutter="2">
        <el-col :span="10">
          <el-form-item prop="couponName" label="券名称">
            <el-input v-model="couponForm.couponName" placeholder="券名称" :maxlength="15" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="couponTag" label="券标签">
            <el-input v-model="couponForm.couponTag" placeholder="券标签" :maxlength="4" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="2">
        <el-col :span="8">
          <el-form-item prop="orderType" label="订单类型">
            <el-select v-model="couponForm.orderType" placeholder="订单类型" style="width: 100%;" @change="changeOrderType">
              <el-option v-for="item in orderTypeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <template v-if="couponForm.orderType === 'SUBSCRIPTION_ORDERS'">
          <el-col :span="4">
            <el-form-item prop="subOrderType.type" label-width="0" :rules="rules.subOrderType">
              <el-select v-model="couponForm.subOrderType.type" placeholder="计划订单" style="width: 100%;">
                <el-option v-for="item in subPlanOrder" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="couponForm.subOrderType.type === 'PLAN_PERIOD'">
            <el-form-item prop="subOrderType.period" label-width="0" :rules="rules.subOrderPeriod">
              <el-select v-model="couponForm.subOrderType.period" placeholder="时间周期" style="width: 100%;">
                <el-option v-for="item in planOrderDate" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="couponForm.orderType === 'PRODUCT_ORDERS'">
          <el-col :span="4">
            <el-form-item prop="subOrderType.type" label-width="0" :rules="rules.subOrderProduct">
              <el-select v-model="couponForm.subOrderType.type" placeholder="商品类型" style="width: 100%;">
                <el-option v-for="item in subProductOrder" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="couponForm.subOrderType.type === 'SPECIFIC_PRODUCTS'">
            <el-form-item prop="subOrderType.product_ids" label-width="0" :rules="rules.subOrderProduct">
              <el-select v-model="couponForm.subOrderType.product_ids" multiple placeholder="指定商品" style="width: 100%;">
                <el-option v-for="item in productList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
      <el-form-item prop="distributionMethod" label="发放方式">
        <el-select v-model="couponForm.distributionMethod" placeholder="发放方式">
          <el-option v-for="item in sendTypeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="ruleType" label="券规则">
        <el-select v-model="couponForm.ruleType" placeholder="券规则">
          <el-option value="DISCOUNT" v-if="couponType === 'ORDER_DISCOUNT'" label="折扣" />
          <el-option value="FULL_REDUCTION" label="满减" />
          <el-option value="DIRECT_DEDUCTION" label="立减" />
        </el-select>
      </el-form-item>
      <el-row :gutter="2">
        <template v-if="couponForm.ruleType === 'DISCOUNT'">
          <el-col :span="10">
            <el-form-item label="折扣力度" prop="ruleDetails.discount_rate" :rules="rules.ruleDiscount">
              <el-input-number v-model="couponForm.ruleDetails.discount_rate" :min="0.1" :step="0.1"
                controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="couponForm.ruleType !== undefined">
            <el-form-item label="折扣上限" prop="ruleDetails.max_discount" :rules="rules.ruleDiscountMax">
              <el-input-number v-model="couponForm.ruleDetails.max_discount" :min="1" controls-position="right" />
            </el-form-item>
          </el-col>
        </template>
        <template v-else>
          <el-col :span="10" v-if="couponForm.ruleType === 'FULL_REDUCTION'">
            <el-form-item label="使用门槛" prop="ruleDetails.threshold" :rules="rules.ruleThreshold">
              <el-input-number v-model="couponForm.ruleDetails.threshold" :min="0.1" :step="0.1"
                controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="couponForm.ruleType !== undefined">
            <el-form-item label="抵扣金额" prop="ruleDetails.deduction" :rules="rules.ruleDiscount">
              <el-input-number v-model="couponForm.ruleDetails.deduction" :min="0.1" :step="0.1" :precision="1"
                controls-position="right" />
            </el-form-item>
          </el-col>
        </template>
      </el-row>
      <el-row :gutter="2">
        <el-col :span="10">
          <el-form-item prop="validityType" label="使用时间">
            <el-select v-model="couponForm.validityType" placeholder="使用时间">
              <el-option value="AFTER_DAYS" label="到账后X天" />
              <el-option value="DATE_RANGE" label="指定时间区间" />
              <el-option value="SPECIFIC_DATES" label="特定日期" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="0" prop="validityDetails.days" :rules="rules.validityDate"
            v-if="couponForm.validityType === 'AFTER_DAYS'">
            <el-input-number v-model="couponForm.validityDetails.days" controls-position="right" />
          </el-form-item>
          <el-form-item label-width="0" prop="validityDetails.date" :rules="rules.validityDate"
            v-if="couponForm.validityType === 'DATE_RANGE'">
            <el-date-picker v-model="couponForm.validityDetails.date" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item label-width="0" prop="validityDetails.dates" :rules="rules.validityDate"
            v-if="couponForm.validityType === 'SPECIFIC_DATES'">
            <el-date-picker type="dates" v-model="couponForm.validityDetails.dates" placeholder="选择一个或多个日期" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="2">
        <el-col :span="10">
          <el-form-item prop="usageLimit" label="使用上限">
            <el-select v-model="couponForm.usageLimit" placeholder="使用上限">
              <el-option value="PER_USER" label="每人" v-if="couponType === 'ORDER_DISCOUNT'" />
              <el-option value="PER_DAY" label="每天" v-if="couponType === 'ORDER_DISCOUNT'" />
              <el-option value="PER_USER_PER_DAY" label="每人每天" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10" v-if="couponForm.usageLimit">
          <el-form-item label-width="0" prop="usageLimitValue">
            <el-input-number v-model="couponForm.usageLimitValue" controls-position="right" :min="1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="couponForm.orderType === 'PRODUCT_ORDERS' ? '券数量' : '库存总量'" prop="totalQuantity">
        <el-input-number v-model="couponForm.totalQuantity" controls-position="right" :min="1" />
      </el-form-item>
      <el-form-item prop="alertSwitch" label="预警开关">
        <el-switch v-model="couponForm.alertSwitch" />
      </el-form-item>
      <el-form-item label="预警阈值" v-if="couponForm.alertSwitch" prop="stockAlertThreshold">
        <el-input-number v-model="couponForm.stockAlertThreshold" controls-position="right" :min="1"
          placeholder="预警阈值" />
      </el-form-item>
      <el-form-item label="预警邮箱" v-if="couponForm.alertSwitch" prop="stockAlertEmail">
        <el-input v-model="couponForm.stockAlertEmail" placeholder="预警邮箱" />
      </el-form-item>
    </el-form>
    <el-descriptions title="优惠券详情" :column="1" border v-if="pageType === 'view'" width="800px">
      <el-descriptions-item label="券名称">{{ couponDetail.couponName }}</el-descriptions-item>
      <el-descriptions-item label="订单类型">{{ orderType[couponDetail.orderType] }}</el-descriptions-item>
      <el-descriptions-item label="计划订单" v-if="couponDetail.orderType === 'SUBSCRIPTION_ORDERS'">
        {{ subPlan[couponDetail.subOrderType.type] }}
      </el-descriptions-item>
      <el-descriptions-item label="订单周期"
        v-if="couponDetail.orderType === 'SUBSCRIPTION_ORDERS' && couponDetail.subOrderType.type === 'PLAN_PERIOD'">
        {{planOrderDate.find(item => item.value === couponDetail.subOrderType.period).label}}
      </el-descriptions-item>
      <el-descriptions-item label="商品订单" v-if="couponDetail.orderType === 'PRODUCT_ORDERS'">
        {{ subProduct[couponDetail.subOrderType.type] }}
      </el-descriptions-item>
      <el-descriptions-item label="指定商品"
        v-if="couponDetail.orderType === 'PRODUCT_ORDERS' && couponDetail.subOrderType.type === 'SPECIFIC_PRODUCTS'">
        {{ parseProducts(couponDetail.subOrderType ? couponDetail.subOrderType.product_ids : []) }}
      </el-descriptions-item>
      <el-descriptions-item label="发放方式">
        {{ sendType[couponDetail.distributionMethod] }}
        <el-button v-if="couponDetail.distributionMethod === 'CODE'" @click="downLoadCode">下载券码</el-button>
      </el-descriptions-item>
      <el-descriptions-item label="券规则">{{ ruleType[couponDetail.ruleType] }}</el-descriptions-item>
      <el-descriptions-item label="使用门槛" v-if="couponDetail.ruleType === 'FULL_REDUCTION'">
        {{ couponDetail.ruleDetails.threshold }}
      </el-descriptions-item>
      <el-descriptions-item label="抵扣金额"
        v-if="couponDetail.ruleType === 'FULL_REDUCTION' || couponDetail.ruleType === 'DIRECT_DEDUCTION'">
        {{ couponDetail.ruleDetails.deduction }}
      </el-descriptions-item>
      <el-descriptions-item label="折扣力度" v-if="couponDetail.ruleType === 'DISCOUNT'">
        {{ couponDetail.ruleDetails.discount_rate }}
      </el-descriptions-item>
      <el-descriptions-item label="折扣上限" v-if="couponDetail.ruleType === 'DISCOUNT'">
        {{ couponDetail.ruleDetails.max_discount }}
      </el-descriptions-item>
      <el-descriptions-item label="使用时间">{{ calcUseTimeText(couponDetail.validityType) }}</el-descriptions-item>
      <el-descriptions-item label="使用上限">
        {{ useLimit[couponDetail.usageLimit] }}使用{{ couponDetail.usageLimitValue }}
      </el-descriptions-item>
      <el-descriptions-item label="库存总量">
        {{ couponDetail.totalQuantity }}
        <el-popover placement="bottom" trigger="click" v-model="showpopover"
          v-if="couponDetail.distributionMethod === 'CODE'">
          <div class="toolTipNumber">
            <el-input-number controls-position="right" v-model="addNumber" :min="1" />
            <div class="toolTipNumberFooter">
              <el-button type="primary" @click="addCouponNumber">确定</el-button>
              <el-button @click="showpopover = false">取消</el-button>
            </div>
          </div>
          <el-button slot="reference">添加库存</el-button>
        </el-popover>
      </el-descriptions-item>
      <el-descriptions-item label="预警阈值" v-if="couponDetail.alertSwitch === '0'">
        {{ couponDetail.stockAlertThreshold }}
      </el-descriptions-item>
      <el-descriptions-item label="预警邮箱" v-if="couponDetail.alertSwitch === '0'">
        {{ couponDetail.stockAlertEmail }}
      </el-descriptions-item>
    </el-descriptions>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" v-if="pageType === 'form'" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { orderType, subPlanOrder, planOrderDate, subProductOrder, sendType, ruleType, subPlan, subProduct, useLimit } from '@/constants/coupon';
import { saveCouponItem, queryCouponItemDetail, plusCouponNumber, exportCouponCode } from '@/api/coupon';
import { getListForSelect } from "@/api/invite/inviteCampaign";
import moment from 'moment';

export default {
  props: ['couponType', 'getTableData'],
  data() {
    return {
      subPlanOrder,
      planOrderDate,
      subProductOrder,
      pageType: 'form',
      dialogVisible: false,
      orderType,
      sendType,
      ruleType,
      subPlan,
      subProduct,
      useLimit,
      orderTypeList: [],
      sendTypeList: [],
      couponForm: {
        couponName: undefined,
        couponTag: undefined,
        orderType: undefined,
        subOrderType: {
          type: '',
          period: '',
          product_ids: [],
        },
        distributionMethod: undefined,
        ruleType: undefined,
        ruleDetails: {
          discount_rate: undefined,
          max_discount: undefined,
          threshold: undefined,
          deduction: undefined,
        },
        validityType: undefined,
        validityDetails: {
          validity_type: undefined,
          days: undefined,
          date: [],
          dates: []
        },
        usageLimit: undefined,
        usageLimitValue: undefined,
        totalQuantity: undefined,
        alertSwitch: false,
        stockAlertThreshold: undefined
      },
      rules: {
        couponName: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
        orderType: [{ required: true, message: '请选择订单类型', trigger: 'blur' }],
        subOrderType: [{ required: true, message: '请选择计划订单', trigger: 'blur' }],
        subOrderPeriod: [{ required: true, message: '请选择计划周期', trigger: 'blur' }],
        subOrderProduct: [{ required: true, message: '请选择商品', trigger: 'blur' }],
        distributionMethod: [{ required: true, message: '请选择发放方式', trigger: 'blur' }],
        ruleType: [{ required: true, message: '请选择券规则', trigger: 'blur' }],
        ruleDeduction: [{ required: true, message: '请输入抵扣金额', trigger: 'blur' }],
        ruleDiscount: [{ required: true, message: '请输入折扣力度', trigger: 'blur' }],
        ruleDiscountMax: [{ required: true, message: '请输入折扣上限', trigger: 'blur' }],
        ruleThreshold: [{ required: true, message: '请输入使用门槛', trigger: 'blur' }],
        validityType: [{ required: true, message: '请选择使用时间', trigger: 'blur' }],
        validityDate: [{ required: true, message: '请设置使用时间', trigger: 'blur' }],
        usageLimit: [{ required: true, message: '请选择使用上限', trigger: 'blur' }],
        usageLimitValue: [{ required: true, message: '请设置上限数量', trigger: 'blur' }],
        totalQuantity: [{ required: true, message: '请设置库存总量', trigger: 'blur' }],
        stockAlertThreshold: [{ required: true, message: '请设置预警数值', trigger: 'blur' }],
        stockAlertEmail: [{ required: true, message: '请设置预警数值', trigger: 'blur' }],
      },
      couponDetail: {
        validityDetails: {
          days: '',
          date: [],
          dates: []
        }
      },
      showpopover: false,
      addNumber: 1,
      productList: []
    }
  },
  created() {
    this.getProductList()
    this.createSelectData(orderType, 'orderTypeList');
    this.createSelectData(sendType, 'sendTypeList');
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        Object.assign(this.$data.couponForm, this.$options.data().couponForm)
        Object.assign(this.$data.couponDetail, this.$options.data().couponDetail)
      }
    }
  },
  methods: {
    // 解析商品
    parseProducts(ids = []) {
      return ids.map(id => {
        const product = this.productList.find(item => item.value === id)
        return product ? product.label : `下架商品ID（id）`
      }).join(',')
    },
    async getProductList() {
      const { code, rows } = await getListForSelect({})
      if (code !== 200) return;
      this.productList = rows.map(item => ({ label: item.spuName, value: item.id }))
    },
    // 解析JSON数据
    parseJson(json) {
      return JSON.parse(json || '{}');
    },
    showModal(type) {
      this.pageType = type
      this.dialogVisible = true
    },
    closeDialog() {
      if (this.pageType === 'form') {
        this.$refs.couponForm.resetFields();
      }
      this.dialogVisible = false;
    },
    changeFormValue(value) {
      this.couponForm = value;
      this.showModal('form');
    },
    createSelectData(source, current) {
      // 这个方法是将枚举数据转换成list数据
      const typeList = [];
      Object.keys(source).map(item => {
        const typeItem = {
          value: item,
          label: source[item]
        };
        typeList.push(typeItem)
      })
      this[current] = typeList;
    },
    changeOrderType() {
      this.couponForm.subOrderType = {
        type: '',
        period: '',
        product_ids: [],
      }
      this.couponForm.usageLimit = undefined;
      this.couponForm.usageLimitValue = undefined;
      if (this.couponForm.ruleType) {
        this.$refs.couponForm.fields.forEach(field => {
          if (field.prop === 'ruleType') {
            field.resetField(); // 重置特定字段
          }
        });
      }
    },
    async queryCouponDetail(batchId) {
      const { code, data } = await queryCouponItemDetail({ batchId })
      if (code !== 200) return;
      this.couponDetail = {
        ...data,
        subOrderType: JSON.parse(data.subOrderType),
        ruleDetails: JSON.parse(data.ruleDetails),
        validityDetails: JSON.parse(data.validityDetails),
      }
      console.log(this.couponDetail, '==== couponForm')
      this.pageType = 'view';
      this.dialogVisible = true;
    },
    calcUseTimeText(type) {
      const typeText = {
        AFTER_DAYS: this.couponDetail.validityDetails.days ? `到账后${this.couponDetail.validityDetails.days}天` : '',
        DATE_RANGE: this.couponDetail.validityDetails.date && this.couponDetail.validityDetails.date.length > 0 ? `${this.couponDetail.validityDetails.start_date}至${this.couponDetail.validityDetails.end_date}` : '',
        SPECIFIC_DATES: this.couponDetail.validityDetails.dates && this.couponDetail.validityDetails.dates.length > 0 ? this.couponDetail.validityDetails.dates.join('，') : []
      }
      return typeText[type]
    },
    handleSubmit() {
      this.$refs.couponForm.validate((valid) => {
        if (valid) {
          const params = {
            ...this.couponForm
          };
          if (params.validityDetails.date) {
            if (params.validityDetails.date.length <= 0) {
              delete params.validityDetails.date
            } else {
              params.validityDetails.type = params.validityType;
              params.validityDetails.start_date = moment(params.validityDetails.date[0]).format('YYYY-MM-DD');
              params.validityDetails.end_date = moment(params.validityDetails.date[1]).format('YYYY-MM-DD');
            }
          }
          if (params.validityDetails.dates) {
            if (params.validityDetails.dates.length <= 0) {
              delete params.validityDetails.dates
            } else {
              // params.validityDetails.validity_type = params.validityType;
              const newDates = [];
              params.validityDetails.dates.map(item => {
                newDates.push(moment(item).format('YYYY-MM-DD'))
              })
              params.validityDetails.dates = newDates;
              delete params.validityDetails.start_date;
              delete params.validityDetails.end_date;
            }
          }
          params.alertSwitch = params.alertSwitch ? 0 : 1;
          params.subOrderType = JSON.stringify(params.subOrderType);
          params.ruleDetails = JSON.stringify(params.ruleDetails);
          params.validityDetails = JSON.stringify(params.validityDetails);
          params.couponType = this.couponType;
          saveCouponItem({
            ...params
          }).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.closeDialog();
              this.getTableData();
            }
          })
        }
      })
    },
    addCouponNumber() {
      plusCouponNumber({
        batchId: this.couponDetail.batchId,
        number: this.addNumber
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.queryCouponDetail(this.couponDetail.batchId)
        }
      })
    },
    downLoadCode() {
      exportCouponCode({
        batchId: this.couponDetail.batchId,
      }).then(res => {
        const blobUrl = URL.createObjectURL(res);
        const a = document.createElement('a');
        a.href = blobUrl;
        a.download = `${this.couponDetail.couponName}券码`;
        a.click();
        URL.revokeObjectURL(blobUrl);
      })
    }
  }
}
</script>

<style scoped lang="scss">
.toolTipNumber {
  height: auto;

  .toolTipNumberFooter {
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
